package life.freebao.devops.serouter.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import life.freebao.devops.serouter.domain.Message;
import life.freebao.devops.serouter.domain.Text;
import life.freebao.devops.serouter.domain.enumeration.MessageType;
import life.freebao.devops.serouter.page.router.RebootPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;

@Service
public class RebootService {
    private final Logger log = LoggerFactory.getLogger(RebootService.class);
    private final RebootPage rebootPage;
    private final HttpClient httpClient;
    @Value("${application.wecom.router.token:9d44e914-27d2-6161-1c46-79767ef6379c}")
    private String token;

    public RebootService(RebootPage rebootPage, HttpClient httpClient) {
        this.rebootPage = rebootPage;
        this.httpClient = httpClient;
    }

    public Message getMessage(Text text){
        Message.Builder builder = new Message.Builder();
        return builder.text(text).messageType(MessageType.text).build();
    }

    public Map<String, String> sendMessage(String hookUrl, Message message) throws IOException, InterruptedException {
        String requestMessage = new ObjectMapper().writeValueAsString(message);
        log.debug("requestMessage = {}", requestMessage);
        HttpRequest httpRequest = HttpRequest.newBuilder().uri(URI.create(hookUrl)).POST(HttpRequest.BodyPublishers.ofString(requestMessage)).build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        Map<String, String> responseBodyMap = new ObjectMapper().readValue(httpResponse.body(), new TypeReference<Map<String, String>>(){});
        log.debug("responseBodyMap = {}", responseBodyMap);
        return responseBodyMap;
    }
    @Scheduled(cron = "${application.webdriver.router.reboot.normal.cron:0 0 * * * ?}")
    public void rebootRouterNormalTask() throws IOException, InterruptedException {
        String hookUrl = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=".concat(token);
        Text text = new Text.Builder().content("Restarting modem").build();
        Message message = getMessage(text);
        log.debug("message = {}", message);
        Map<String, String> responseMap = sendMessage(hookUrl, message);
        log.debug("responseMap = {}", responseMap);
        log.info("Restarting router...");
        rebootPage.rebootRouter();
    }
    @Scheduled(cron = "${application.webdriver.router.reboot.abnormal.cron:0 0 * * * ?}")
    public void rebootRouterAbnormalTask() throws InterruptedException {
        if (!isBaiduReachable() && !isTencentReachable()) {
            log.info("Network is unreachable. Try to reboot router...");
            rebootPage.rebootRouter();
        }
    }
    public static boolean isBaiduReachable() {
        try {
            return InetAddress.getByName("180.76.76.76").isReachable(10000);
        } catch (IOException e) {
            return false;
        }
    }
    public static boolean isTencentReachable() {
        HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofMillis(10000L)).followRedirects(HttpClient.Redirect.NORMAL).build();
        HttpRequest httpRequest = HttpRequest.newBuilder().uri(URI.create("https://www.tencent.com")).GET().build();
        try {
            HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
            return httpResponse != null;
        } catch (Exception e) {
            return false;
        }
    }
}
